#include<termios.h>                                     
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include <string.h>
#include"interface.h"

	static int ret = 0;
	static int fd;
	static int buf_size = 100;

void serial_init(int fd) //初始化串口的函数
{
    struct termios options;
    tcgetattr(fd, &options);
    options.c_cflag |= (CLOCAL | CREAD);
    options.c_cflag &= ~CSIZE;
    options.c_cflag &= ~CRTSCTS;
    options.c_cflag |= CS8;
    options.c_cflag &= ~CSTOPB;
    options.c_iflag |= IGNPAR;
    options.c_oflag  = 0;
	options.c_lflag  = 0;
	options.c_cc[VEOL] 	= 1;

    cfsetispeed(&options, B115200); 
    cfsetospeed(&options, B115200);
    tcsetattr(fd, TCSANOW, &options);
}

void readbuf(char *readbuf)
{
	char *read_buf = readbuf;
	sleep(1);
	//fflush(fd);	//使用此函数就什么也打印不出来
	ret = read(fd, read_buf, buf_size);
	if(0 > ret)
	{
		perror("read error:");
	}
	printf("%s\n", read_buf);
}

int sendmsg_api(int flag,char *pnum)
{
	char read_buf[buf_size];
	memset(read_buf, 0, buf_size);	
	char *write_buf = {0};
	write_buf = (char *)malloc(buf_size);
	memset(write_buf, 0, buf_size);	
	
	fd = open("/dev/ttyUSB1", O_RDWR|O_NOCTTY|O_NDELAY);//打开文件描述符
	if(fd < 0)
	{
		perror("open fd error!");
		return;
	}
	
	serial_init(fd);	//初始化串口
	
	if(1 == flag)	//打电话
	{
		strcpy(write_buf, "ATD");
		strcat(write_buf, pnum);
		strcat(write_buf, ";\r\n");
		int ret = write(fd, write_buf, strlen(write_buf));
		if(0 > ret)
		{
			perror("write error:");
			return;
		}
		sleep(1);
		readbuf(read_buf);
	}
	
	else if(0 == flag)	//发短信
	{
		strcpy(write_buf, "AT+CMGF=1\r\n");
		ret = write(fd, write_buf, strlen(write_buf));
		if(0 > ret)
		{
			perror("write error:");
			return;
		}
		sleep(1);
		readbuf(read_buf);
		
		strcpy(write_buf, "AT+CSCS=\"GSM\"\r\n");
		ret = write(fd, write_buf, strlen(write_buf));
		if(0 > ret)
		{
			perror("write error:");
			return;
		}
		sleep(1);
		readbuf(read_buf);
		
		strcpy(write_buf, "AT+CMGS=\"");
		strcat(write_buf, pnum);
		strcat(write_buf, "\"\r\n");
		ret = write(fd, write_buf, strlen(write_buf));
		if(0 > ret)
		{
			perror("write error:");
			return;
		}
		sleep(1);
		readbuf(read_buf);
		
		char *ploc = NULL;
	/*	ploc = get_GPS_api();	//此函数参数为gps路径
		if(NULL == ploc)
		{
			printf("error, get gps failed!\r\n");
			return -1;
		}
		strcpy(write_buf, ploc);*/
		
		strcpy(write_buf, "this is my location, please help me \x01a");
		ret = write(fd, write_buf, strlen(write_buf));
		if(0 > ret)
		{
			perror("write error:");
			return;
		}
		sleep(1);
		readbuf(read_buf);
		
	}
	sleep(10);
	close(fd);
}
